package com.gitee.feizns.explore.data_structure.tree.bs.mid;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 面试题32 - III. 从上到下打印二叉树 III
 * @author feizns
 * @since 2020/3/20
 */
public class LevelOrder3 {

    public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
        for (int i = 0; i < 1000000; i++) {
            list.add(i);
        }
        long start = System.nanoTime();
        Collections.reverse(list);
        long end = System.nanoTime();
        System.out.println(end - start);
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new LinkedList<>();
        int level = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        if ( root != null )
            queue.add(root);
        while ( !queue.isEmpty() ) {
            List<Integer> tmp = new LinkedList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                tmp.add(node.val);
                if ( node.left != null )
                    queue.add(node.left);
                if ( node.right != null )
                    queue.add(node.right);
            }
            if ( level++ % 2 == 1 )
                Collections.reverse(tmp);
            ret.add(tmp);
        }
        return ret;
    }

}
